var fs = require('WxFileUtils2');

cc.Class({
    extends: cc.Component,

    properties: {
        fileName :cc.Prefab,
        textContent : cc.Prefab
    },

    onLoad () {
        fs.init();
        this.scrollView = this.node.getChildByName('scrollview').getComponent(cc.ScrollView)
        this.rootPath = CC_WECHATGAME ? wx.env.USER_DATA_PATH : ''
        // this.node.getChildByName('path').getComponent(cc.Label).string = '目录:'+this.rootPath;
        this.showDir(this.rootPath)
    },

    showDir(fold){
        this.currentFold = fold;
        this.node.getChildByName('path').getComponent(cc.Label).string = '目录:'+this.currentFold;
        this.scrollView.content.removeAllChildren();
        fs.readDir(fold,(err,files,folds)=>{
            if(this.rootPath != this.currentFold){
                folds = ['..'].concat(folds)
            }
            for(var i=0; i<folds.length; i++){
                var pre = cc.instantiate(this.fileName);
                this.scrollView.content.addChild(pre);
                pre.getChildByName('t').getComponent(cc.Label).string = '口'
                pre.getChildByName('name').getComponent(cc.Label).string = folds[i].substring(folds[i].lastIndexOf('/')+1);
                pre.getChildByName('size').active =false;
                this.addButtonHandler(this,pre.getComponent(cc.Button),'onClickFold',folds[i]);
                pre.__filename = folds[i]
            }

            for(var i=0; i<files.length; i++){
                var pre = cc.instantiate(this.fileName);
                this.scrollView.content.addChild(pre);
                pre.getChildByName('name').getComponent(cc.Label).string = files[i].name;
                pre.getChildByName('size').getComponent(cc.Label).string = (files[i].size/1000).toFixed(1)+'kb';
                this.addButtonHandler(this,pre.getComponent(cc.Button),'onClickFile',files[i].path);
                pre.__filename = files[i].name
            }
            this.setContentEnable(null)
        })
    },

    setContentEnable(d){
        var children = this.scrollView.content.children
        for(var i=0; i<children.length; i++){
            children[i].getComponent(cc.Button).interactable = children[i].__filename != d
        }
    },

    onClickPath(event,d){
        cc.log('d:',d);
        
        if(d == '..'){
            cc.log('返回上层')
        } else {
            this.setContentEnable(d)
        }
    },

    onClickFile(event,d){
        this.setContentEnable(d)
        this.selectFile = d;
        cc.log('fold:',d);
        var houzhui = this.selectFile.substring(this.selectFile.lastIndexOf('.')+1)
        let isTxt = !(houzhui == 'png' || houzhui == 'jpg');
        var review = this.node.getChildByName('review')
        review.active = true;
        review.getChildByName('image').active = false;
        review.getChildByName('scrollview').active = false;
        review.getChildByName('path').getComponent(cc.Label).string = d.substring(this.rootPath.length);
        var content = cc.find('scrollview/view/content',review)
        content.removeAllChildren();
        var self = this;
        if(isTxt){
            fs.readFile(d,(data)=>{
                review.getChildByName('scrollview').active = true;
                var strs = self.subSectionString(data,50);
                var index = 0;
                var interval = setInterval(function(){
                    for(var i=0; i<10; i++){
                        var pre = cc.instantiate(self.textContent);
                        content.addChild(pre)
                        pre.getComponent(cc.Label).string = strs[index];
                        index++;
                        if(index >= strs.length){
                            cc.log('添加完成')
                            clearInterval(interval);
                            return;
                        }
                    }
                },0.01)
                
                content.getComponent(cc.Layout).updateLayout();
            })
        } else {
            let image = wx.createImage();
            image.onload = () => {
                try {
                    review.getChildByName("image").active = true;
                    let texture = new cc.Texture2D();
                    texture.initWithElement(image);
                    texture.handleLoadedTexture();
                    review.getChildByName('image').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
                } catch (e) {
                    cc.log('读取图片出错:',d)
                }
            };
            image.src = d;
        }
    },

    onClickFold(e,d){
        cc.log('fold:',d);
        if(d == '..'){
            d = this.currentFold.substring(0,this.currentFold.lastIndexOf('/'))
        }
        this.showDir(d);
    },  
    onClickCloseReview(){
        var review = this.node.getChildByName('review')
        review.active = false;
        
    },
    onClickDeleteFile(){
        cc.log('onClickDeleteFile')
        var review = this.node.getChildByName('review')
        review.active = false;
        if(this.selectFile){
            var self =this;
            fs.removeFile(this.selectFile,function(){
                self.showDir(self.currentFold);
            })
            this.selectFile = null;
        }
    },
    onClickDeleteFold(){
        cc.log('onClickDeleteFold')
        var wft = require('WxFileUtils');
        var self = this;
        wft.clearFile(this.currentFold,function(a){
            cc.log('删除进度:',a);
            self.showProgress(a);
        },function(){
            var p = self.currentFold.substring(0,self.currentFold.lastIndexOf('/'))
            self.hideProgress();
            self.showDir(p);
            cc.log('删除完成')
        })
    },
    showProgress(a){
        wx.showLoading({title:'删除中:'+Math.floor(a*100)+'%',mask:true})
    },
    hideProgress(){
        wx.hideLoading();
    },
    onClickBack(){
        cc.director.loadScene('Main');
    },

    addSingleButton(node,type){
        var c = node.getComponent(type);
        if(!c){
            c = node.addComponent(type);
            c.transition = cc.Button.Transition.SCALE
        }
        return c;
    },
    addButtonHandler(target,btnNode,func,tag){
        if(!target){
            console.warn('没有节点怎么添加触摸')
            return;
        }
        var name = target.name.substring(target.name.indexOf('<')+1,target.name.indexOf('>'));
        var handler = new cc.Component.EventHandler();
        handler.target = target;
        handler.component = name;
        handler.handler = func;
        handler.customEventData = tag;
        var button = btnNode instanceof cc.Button ? btnNode :  this.addSingleButton(btnNode,cc.Button);
        button.clickEvents.push(handler)
        return button
    },
    subSectionString(text,cutlen){
        var id = 0;
        var strs = [];
        var str = '' 
        var len = 0;
        for (var i=0; i<text.length; i++) {    
            var c = text.charCodeAt(i);
            if (c>127 || c==94) {    
                len += 2;    
            } else {    
                len ++;    
            }
            if(len>cutlen || c == '\n') {
                str += text.substring(id,i);
                strs.push(str);
                str = '';
                len = 0;
                id = i;
            }
        } 
        str += text.substring(id,text.length);
        if(str.length)
        {
            strs.push(str);
        }
        return strs;
    },
});
